import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, Content, ToastController, LoadingController, Select} from 'ionic-angular';

import * as moment from 'moment';
import $ from "jquery";
import {CallNumber} from "@ionic-native/call-number";

import {Condition, ExportClient, FilterResponse} from '../../../model/pages/client/client-filter/client-filter.model';
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {ClientFilterListProvider} from '../../../providers/client/client-filter-list/client-filter-list';
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {ClientFilterWayModel} from "../../../model/pages/client/client-list/client.model";
import {ClientFilterComponent} from "../../../components/pages/client/client-filter/client-filter.component";

import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {LoadingService} from "../../../services/common/loading.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

@IonicPage()
@Component({
    selector: 'page-client-filter-list',
    templateUrl: 'client-filter-list.html',
    providers: [
        CallNumber,
        ClientNoteEditProvider,
        ClientFilterListProvider,
        CallNumberService,
        LoadingService
    ]
})
export class ClientFilterListPage extends InfiniteScrollModel {
    @ViewChild(Content) content: Content;
    @ViewChild('multiMobile') multiMobile: Select;

    private pageStatus: number;

    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 10 / 100) + 'px';
    }

    // 客户筛选输入
    private condition: Condition = new Condition();
    // 客户筛选输出
    public exportClient: Array<any>;
    // 筛选响应
    private filterResponse: FilterResponse = new FilterResponse();
    // infiniteScroll对象
    private infiniteScroll = null;
    // 加载
    loading: any;
    // 是否有请求记录
    requestStatus: boolean = false;
    // 当前电话列表
    isViewDidLoad = false;
    isArriveBottom = false;
    isLoaded: boolean = false;
    orderType: string;
    @ViewChild('clientFilterTool') clientFilterTool: ClientFilterComponent;
    isScrolling = false;
    // 当前客户ID
    clientNum: string;
    currentClient;
    currentMobileList;
    currentMobile;
    filterConditionsShow = true;
    clientSortPage = ClientFilterWayModel.ClientFilterListPage;
    dataItemSearchWrapper = {
        isSearchWrapper:true
    };
    //正在刷新
    refreshing:boolean = false;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public toastCtrl: ToastController,
                public callNumber: CallNumber,
                public loadCtr: LoadingController,
                public changeRef: ChangeDetectorRef,
                public clientNoteEditProvider: ClientNoteEditProvider,
                private callNumberService: CallNumberService,
                public clientFilterListProvider: ClientFilterListProvider,
                public adpActionSheetController:AdpActionSheetController,
                public load: LoadingService) {
        super();
        this.exportClient = [this.dataItemSearchWrapper];
    }

    public backHandle = () => this.backClickHandle();

    ionViewDidLoad() {
        this.isViewDidLoad = true;
        this.condition.keyword = null;
        this.pageStatus = 2;
        this.condition = this.navParams.get('data');
        this.condition.pageNum = 1;
        this.getFilterData(this.condition, true);
    }

    ionViewDidEnter() {
        let flag = MessageBushService.getMessage(MessageBushService.keys.clientFilterListUpdated);
        if (flag == "1" && !this.isViewDidLoad && this.navCtrl.getPrevious().id == 'ClientFilterListPage') {
            MessageBushService.setMessage(MessageBushService.keys.clientFilterListUpdated, "0");
            this.condition.pageNum = 1;
            this.getFilterData(this.condition, true);
        }
        this.isViewDidLoad = false;

    }

    /**
     * 筛选请求
     * @param {Condition} condition
     * @param {boolean} fresh
     * @param {any} callback
     */
    getFilterData(condition: Condition, fresh: boolean, callback = null) {
        // this.load.showLoading();
        this.isArriveBottom = false;
        fresh ? this.load.showProLoading() : null;
        this.condition.pageSize = 0;
        this.condition.pageNum = 1;
        this.condition.orderType = this.orderType;
        this.clientFilterListProvider.getClientFilter(this.condition, 1).subscribe(result => {
            this.condition.pageSize = result.total;

            this.clientFilterListProvider.getClientFilter(this.condition, 0).subscribe((res) => {
                this.filterResponse = res;
                this.isLoaded = true;
                this.exportClient = this.filterResponse.list;
                this.requestStatus = true;
                if(this.exportClient.indexOf(this.dataItemSearchWrapper) == -1){
                    this.exportClient.unshift(this.dataItemSearchWrapper);
                }
                console.log(this.exportClient);
                callback ? callback() : null;
                this.load.dismissProLoading();
            }, error => {
                this.load.errorDismiss();
                this.requestStatus = true;
                callback ? callback() : null;
            })
        }, error=> {
            this.load.errorDismiss();
            if(error.status==500){
                this.exportClient=[this.dataItemSearchWrapper]
            }
            this.isLoaded=true;
            callback ? callback() : null;
        });
    }

    // 分页加载更多
    getMore(infiniteScroll) {
        this.infiniteScroll = infiniteScroll;
        infiniteScroll.complete();
        this.isArriveBottom = true;
        // } else {
        // infiniteScroll.waitFor(this.getNextPageData());
        // }
    }


    // 范围值大小对换
    checkValue(field1, field2, str) {
        let num1 = Number(JSON.parse(JSON.stringify(field1)));
        let num2 = Number(JSON.parse(JSON.stringify(field2)));
        if (String(num1).length && String(num2).length) {
            if (num1 > num2) {
                let max = num1;
                num1 = num2;
                num2 = max;
                console.log(num1, num2)
            }
        }
        switch (str) {
            case 'age':
                this.condition.ageFrom = String(num1);
                this.condition.ageTo = String(num2);
                break;
            case 'total':
                this.condition.totalPremFrom = String(num1);
                this.condition.totalPremTo = String(num2);
                break;
            case 'claim':
                this.condition.claimAmtFrom = String(num1);
                this.condition.claimAmtTo = String(num2);
        }
    }


    // 下拉刷新
    doRefresh(refresher) {
        this.refreshing = true;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        this.getFilterData(this.condition, false, () => {
            this.refreshing = false;
            this.filterConditionsShow = true;
            refresher.complete();
        })
    }

    searchedHandle(searchKeyword){
        this.condition.pageNum = 0;
        this.condition.keyword = searchKeyword;
        this.getFilterData(this.condition, true);
    }

    // 到客户详情
    goToClientDetail(role, id) {
        const clientRole = role;
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: id,
            role: clientRole
        })
    }

    //调用原生打电话
    nativeCallPhone(mobilePhone?: string) {
        if (mobilePhone) {
            this.currentMobile = mobilePhone;
        }
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentClient.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentClient.clientId));
    }

    /**
     * 打电话
     */
    callClickHandle(item) {
        this.currentClient = item;
        this.currentMobileList = item.mobilePhone;
        if (!this.currentMobileList || this.currentMobileList.length < 1) return;
        if (this.currentMobileList.length === 1 && this.currentMobileList[0].mobile) {
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }else{
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.currentMobile = phoneNumItem.mobile;
                        this.nativeCallPhone();
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }

    }

    /**
     *  返回
     */
    backClickHandle() {
        if (this.navParams.get('callback')) {
            this.navParams.get('callback')(this.condition).then(() => this.navCtrl.pop());
        } else {
            this.navCtrl.pop();
        }
    }
    filterClicked(){
        this.backClickHandle();
    }
    // scroll到顶部
    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }

    /**
     * 提示框
     *
     * @private
     * @param {any} msg 提示的消息
     * @memberof ScheduleAddPage
     */
    showToast(msg) {
        let toast = this.toastCtrl.create({
            message: msg,
            position: 'middle',
            duration: 2000
        });
        toast.present();
        toast.dismissAll();
    }

    // 显示加载
    showLoading() {
        /*this.loading = this.loadCtr.create({
            spinner: 'circles',
            content: "加载中",
        });
        this.loading.present();*/
    }

    // 结束加载
    dismissLoading() {
        /*if (this.loading) {
            this.loading.dismiss();
            this.loading = null;
        }*/
    }

    /**
     * 格式化千分位
     * @param numP
     * @returns {string}
     */
    toThousands(numP) {
        let num = (numP || 0).toString(), result = '';
        while (num.length > 3) {
            result = ',' + num.slice(-3) + result;
            num = num.slice(0, num.length - 3);
        }
        if (num) {
            result = num + result;
        }
        return result;
    }

    selectChangeHandle(e) {
        this.orderType = e.value;
        this.getFilterData(this.condition, true);
    }

    ionViewWillLeave() {
        this.condition.keyword = '';
        this.clientFilterTool.destroy();
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        const temp1=dimensions.scrollHeight-dimensions.scrollTop-dimensions.contentHeight<100;
        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }
    scrollStart(){
        this.isScrolling = true;
    }
    scrollEnd(){
        this.isScrolling = false;
    }

    contentTouchEnd(){
        setTimeout(() => {
            if(!this.refreshing) {
                this.filterConditionsShow = true;
            }
        },500);
    }

    showNoData () {
        return !this.exportClient[1]  && this.isLoaded;
    }

}
